from interface.api import api
from lib.jenkins_proxy import JenkinsProxy
from jenkins import TimeoutException
import logging
from utils.const import *
from const import IS_DEBUG

logger = logging.getLogger()

class JenkinsApi(api):

    def __init__(self, param = {}):
        """
        """
        url = param.get("url", "")
        user = param.get("user", "")
        token = param.get("token", "")
        self._path = param.get("path", "")
        self._jenkins = JenkinsProxy(base_url = url, username=user, token=token)

    def create_task(self, param):
        res = self._jenkins.build_job(self._path, param)
        return res.get("build_no", 0), res.get("url", "")
    
    def get_task_info(self,param = {}):
        try:
            if IS_DEBUG:
                logger.info(param)
            build_no = param.get("task_id")
            res = self._jenkins.get_build_info(self._path, build_no)
            if IS_DEBUG:
                logger.info(res)
            if res.get("executor") != None:
                return {"errno": ErrProcess}
            else:
                # 获取环境变量
                envMap = self._jenkins.get_build_env(self._path, build_no)
                if IS_DEBUG:
                    logger.info(envMap)
                envMap = envMap.get("envMap")
                result = envMap.get("build_res", {})
                return {
                    "errno": ErrOk, 
                    "data": {
                        "task_no": build_no, 
                        "check_result": result,
                        "task_log": "this is log",
                        "task_url": envMap["BUILD_URL"]
                    }
                }
        except TimeoutException:
            return {"errno": ErrProcess}
        except Exception as e:
            if IS_DEBUG:
                logger.info(str(e))